import request from "@/router/axios"
import Mock from "mockjs";

const aa = Mock.mock({
    "list|60-100":[
        {
            id:'@id()',
            comName:'@cword(2, 5)',
            comStyle:'@pick(["儿童玩具","手机","相机","平板","水果","服饰","电脑"])',
            comPrice:'@integer(100,5000)',
            comNum:'@integer(1,500)',
            editTime:'@datetime',
        }
    ]
})
// 定义一个接口叫/list
Mock.mock(/\/list/ ,config=>{
    return {
        data:{
            list:aa.list,
            code:200,
        }
    }
})
export const shopListMock = ()=>request({
    url:"/list",
    method:"get"
})

// 分页
export const shopList= (data)=> request({
    url:"/shopList",
    method:"post",
    data
})
Mock.mock(/\/shopList/,config=>{
    console.log(JSON.parse(config.body))
    let {currentPage ,pageSize} = JSON.parse(config.body);
    // 获取到list的数据里面tableList
    let _list = aa.list;
    // 总条数
    let total = _list.length;
    // 根据当前第几页 和一页显示几条 返回相应数据
    // user返回的数据
    let lists= _list.filter(function(item,index) {
       return index<pageSize*currentPage && index>=pageSize*(currentPage -1)
    });
    return{
        data:{
            lists , total
        }
    }
})
//添加和编辑
export const createList= (data)=> request({
  url:"/createList",
  method:"post",
  data
})
Mock.mock(/\/createList/,config => {
      let obj = JSON.parse(config.body);
      if (obj.id) {
        aa.list.some(u => {
          if (u.id === obj.id) {
            u.comName = obj.comName
            u.comStyle = obj.comStyle
            u.comPrice=obj.comPrice
            u.comNum=obj.comNum
            return true
          }
        })
        return {
          code: 200,
          message: '修改成功'
        }
      }else{
        obj.id = Mock.Random.id()
        obj.editTime = Mock.mock('@now')
        aa.list.unshift(obj)

        return {
          code: 200,
          message: '添加成功'
        }
      }

    })
          // 删除
export const deleteList= (data)=> request({
  url:"/deleteList",
  method:"post",
  data
})
Mock.mock(/\/deleteList/,config => {
  let obj = JSON.parse(config.body);
  // aa.list = aa.list.filter(u => u.id != obj.id)
  aa.list = aa.list.filter(function (val) {
    console.log(val);
    return val.id != obj.id; // 过滤掉前台传过来的id对应的相应数据，并重新返回
});
  return {
    data:aa.list,
    code: 200,
    message: '删除成功'
  }
})

